package br.biofoco.p2p.bootstrap;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import br.biofoco.p2p.config.ConfigConstants;

public class AppConfig {

	private File spool;
	private final String CONFIG_DIR;
	private File output;
	private String path;
	
	private static final Logger LOGGER = LoggerFactory.getLogger(AppConfig.class);

	public AppConfig() {
		
		CONFIG_DIR = System.getProperty("config.dir", ConfigConstants.CONFIG_DIR);
		
		try {
			SAXReader reader = new SAXReader();

			Document doc = reader.read(getInputStream(ConfigConstants.APP_CONFIG));
			Element root = doc.getRootElement();
			
			Element spoolElement = root.element("spool-directory");			
			spool = new File(spoolElement.getText());
			
			Element outElement = root.element("output-directory");			
			output = new File(outElement.getText());
			
			path = root.element("path").getText();
			
			
		}
		catch (Exception e) {
			//e.printStackTrace();
			LOGGER.error(e.getMessage());
			System.exit(0);
		}
	}
	
	private InputStream getInputStream(String filename) throws FileNotFoundException {
		return new FileInputStream(CONFIG_DIR + File.separator + filename);
	}	

	/**
	 * A directory where to put temporary files for peer retrieval. Warn: if
	 * using Ftp then each peer should have access to this directory!
	 * 
	 * Use a disposable path like /tmp
	 * 
	 * @return
	 */
	public File getSpoolDirectory() {
		return spool;
	}

	/**
	 * An internal path used by the app to process the files
	 * 
	 * @return
	 */
	public File getOutputDirectory() {
		return output;
	}

	/**
	 * Absolute path of the app.
	 * 
	 * @return
	 */
	public String getPath() {
		return path;
	}

	public String getFtpUsername() {
		return "biofoco";
	}

	public String getFtpPassword() {
		return "biofoco2010";
	}
	
	public String getTorrentFileDirectory() {
		return "torrent";
	}

}
